package com.snow.springboot.service;

import com.github.pagehelper.PageHelper;
import com.snow.springboot.dao.DiagnoseDataMeshMapper;
import com.snow.springboot.dao.DiagnoseInfoMapper;
import com.snow.springboot.pojo.domain.DiagnosExcelInfo;
import com.snow.springboot.pojo.domain.DiagnoseDataMesh;
import com.snow.springboot.pojo.domain.DiagnoseInfo;
import com.snow.springboot.pojo.domain.PageBean;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

/**
 * @Package: com.snow.springboot.service
 * @ClassName: DiagonseService
 * @Description:DiagonseService
 * @author: lurui
 * @Date: 2018/10/26 上午9:15
 * @version:
 */
@Service
public class DiagnoseService {
    private static final Logger LOGGER = LoggerFactory.getLogger(DiagnoseService.class);
    public static final String MEDICAL_2 = "medical2";
    public static final String NCMS = "ncms";
    public static final String CODE = "code";
    public static final String MESSAGE = "message";

    @Autowired
    private DiagnoseDataMeshMapper mapper;

    @Autowired
    private DiagnoseInfoMapper diagnoseInfoMapper;

    @Autowired
    private TransportClient transportClient;
    @Autowired
    private ExcelService excelService;
    @Autowired
    private DiagnoseExcelListener diagnoseListener;


    /**
     * @Description:通过主键ID查询诊断信息
     * @MethodName: getDiagnoseDataMesh
     * @Param: [diagnoseId]
     * @Return: com.snow.springboot.pojo.domain.DiagnoseDataMesh
     * @Author: lurui
     * @Date: 2018/10/26 上午10:29
     */
    public DiagnoseDataMesh getDiagnoseDataMesh(String diagnoseId) {
        return this.mapper.selectByPrimaryKey(diagnoseId);
    }


    /**
     * @Description: 查询诊断书列表
     * @MethodName: getDiagnoseList
     * @Param: []
     * @Return: com.snow.springboot.pojo.domain.PageBean
     * @Author: lurui
     * @Date: 2018/10/26 上午11:20
     */
    public PageBean<DiagnoseInfo> getDiagnoseList(Integer page, Integer size) {
        PageHelper.startPage(page, size);
        List<DiagnoseInfo> diagnoseInfos = diagnoseInfoMapper.listDiagnoseByPage();
        return new PageBean<>(diagnoseInfos);
    }


    /**
     * @Description: 保存诊断书信息
     * @MethodName: saveDiagnoseInfo
     * @Param: [diagnoseInfo]
     * @Return: boolean
     * @Author: lurui
     * @Date: 2018/10/30 4:36 PM
     */
    @Transactional(rollbackFor = Throwable.class)
    public boolean saveDiagnoseInfo(DiagnoseInfo diagnoseInfo) {
        int result = diagnoseInfoMapper.insertSelective(diagnoseInfo);
        return 1 == result;
    }


    @Transactional(rollbackFor = Throwable.class)
    public boolean updateDiagnose(DiagnoseInfo diagnoseInfo) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        if (null == diagnoseInfo) {
            return false;
        }
        for (int i = 1; i < 12; i++) {
            String getMessage = "getDiagnose" + i + "Info";
            String setCode = "setDiagnose" + i + "Code";
            String content = (String) diagnoseInfo.getClass().getMethod(getMessage, new Class[]{}).invoke(diagnoseInfo, new Object[]{});
            if (null == content || "".equals(content)) {
                continue;
            }
            String result = this.getResult(content);
            diagnoseInfo.getClass().getMethod(setCode, new Class[]{String.class}).invoke(diagnoseInfo, new Object[]{result});
        }
        //设置数据状态为已匹配
        diagnoseInfo.setState("2");
        LOGGER.info("diagnoseDataMesh:{}", diagnoseInfo.toString());
        int flag = this.diagnoseInfoMapper.updateByPrimaryKeySelective(diagnoseInfo);
        if (1 == flag) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * @Description: 解析Excel, 得到List
     * @MethodName: getDiagnosesByExcel
     * @Param: [filePath]
     * @Return: java.util.List<com.snow.springboot.pojo.domain.DiagnoseInfo>
     * @Author: lurui
     * @Date: 2018/10/30 7:43 PM
     */
    public List<DiagnoseInfo> getDiagnosesByExcel(String filePath) {
        return excelService.readFromFile(filePath, diagnoseListener, DiagnosExcelInfo.class);
    }


    /**
     * @Description:根据诊断信息查找最佳匹配code
     * @MethodName: getResult
     * @Param: [content]
     * @Return: java.lang.String
     * @Author: lurui
     * @Date: 2018/10/26 上午9:33
     */
    private String getResult(String content) {
        if (StringUtils.isEmpty(content) || "".equals(content)) {
            return null;
        }
        SearchRequestBuilder srb = transportClient.prepareSearch(MEDICAL_2).setTypes(NCMS);
        SearchResponse sr = srb.setQuery(QueryBuilders.matchQuery("message", content).analyzer("ik_max_word"))
                .setFetchSource(new String[]{CODE, MESSAGE}, null)
                .execute()
                .actionGet();
        SearchHits hits = sr.getHits();
        String result = null;
        if (hits.getTotalHits() > 0) {
            SearchHit hit = hits.getAt(0);
            if (null == hit) {
                result = "error";
            } else {
                Map<String, Object> data = hit.getSource();
                result = (String) data.get("code");
                if (null == result || "".equals(result)) {
                    result = "error";
                }
            }
        }
        return result;
    }

}
